package com.example.common.core.exception;

import com.example.common.core.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常统一处理
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class MyExceptionHandler {

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(LinkerException.class)
    public Result handleLinkerException(LinkerException e){
        log.error(e.getMessage(), e);
        return Result.failure(e.getMessage());
    }

    /**
     * 处理自定义系统异常
     */
    @ExceptionHandler(SystemException.class)
    public Result handleSystemException(SystemException e){
        log.error(e.getMessage(), e);
        return Result.sysFailure(e.getMessage());
    }

    /**
     * 入参检测异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return Result.failure("参数不正确："+ message);
    }

    /**
     * 通用异常处理
     */
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e){
        log.error(e.getMessage(), e);
        return Result.failure("操作失败："+e.getMessage());
    }

}
